package com.zh.harmony.mvvm.ability;

import com.zh.harmony.lifecycle.Lifecycle;
import com.zh.harmony.lifecycle.LifecycleOwner;
import com.zh.harmony.lifecycle.LifecycleRegistry;
import com.zh.harmony.lifecycle.ReportFragment;
import com.zh.harmony.viewmodel.ViewModelStore;
import com.zh.harmony.viewmodel.ViewModelStoreOwner;
import ohos.aafwk.ability.LifecycleStateObserver;
import ohos.aafwk.ability.fraction.FractionAbility;
import ohos.aafwk.content.Intent;
import ohos.utils.PacMap;

/**
 * 支持ViewModel的Ability
 */
public class ComponentAbility extends FractionAbility implements LifecycleOwner, ViewModelStoreOwner {
    private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
    private ViewModelStore mViewModelStore;

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        //注入声明周期分发
        ReportFragment.injectIfNeededIn(this);
        //恢复ViewModel
        NonConfigurationInstances nc =
                (NonConfigurationInstances) getLastStoredDataWhenConfigChanged();
        if (nc != null && nc.viewModelStore != null && mViewModelStore == null) {
            mViewModelStore = nc.viewModelStore;
        }
        getLifecycle().addObserver(new LifecycleStateObserver() {
            @Override
            public void onStateChanged(ohos.aafwk.ability.Lifecycle.Event event, Intent intent) {
                if (event == ohos.aafwk.ability.Lifecycle.Event.ON_STOP) {
                    //销毁时，没有发生配置重建时，才清理ViewModelStore
                    if (!isUpdatingConfigurations()) {
                        getViewModelStore().clear();
                    }
                }
            }
        });
    }

    @Override
    public Lifecycle getLifeCycle() {
        return mLifecycleRegistry;
    }

    @Override
    public void onSaveAbilityState(PacMap outState) {
        mLifecycleRegistry.markState(Lifecycle.State.CREATED);
        super.onSaveAbilityState(outState);
    }

    /**
     * 配置存储类
     */
    static final class NonConfigurationInstances {
        /**
         * 自定义数据
         */
        Object custom;
        /**
         * ViewModelStore实例
         */
        ViewModelStore viewModelStore;
    }

    /**
     * Ability的配置改变时，可以保存自定义数据
     */
    public Object onRetainCustomNonConfigurationInstance() {
        return null;
    }

    /**
     * 获取保存的自定义数据
     */
    public Object getCustomStoreDataWhenConfigInstance() {
        NonConfigurationInstances nc = (NonConfigurationInstances) getLastStoredDataWhenConfigChanged();
        if (nc == null) {
            return null;
        }
        return nc.custom;
    }

    @Override
    public Object onStoreDataWhenConfigChange() {
        //Ability的配置改变，保存自定义数据和ViewModel
        Object custom = onRetainCustomNonConfigurationInstance();
        ViewModelStore viewModelStore = mViewModelStore;
        if (viewModelStore == null) {
            NonConfigurationInstances nc =
                    (NonConfigurationInstances) getLastStoredDataWhenConfigChanged();
            if (nc != null) {
                viewModelStore = nc.viewModelStore;
            }
        }
        if (viewModelStore == null && custom == null) {
            return null;
        }
        NonConfigurationInstances nci = new NonConfigurationInstances();
        nci.custom = custom;
        nci.viewModelStore = viewModelStore;
        return nci;
    }

    @Override
    public ViewModelStore getViewModelStore() {
        if (getAbilityPackage() == null) {
            throw new IllegalStateException("Your ability is not yet attached to the "
                    + "AbilityPackage instance. You can't request ViewModel before onStart call.");
        }
        if (mViewModelStore == null) {
            //从保存的配置信息中获取ViewModel
            NonConfigurationInstances nc =
                    (NonConfigurationInstances) getLastStoredDataWhenConfigChanged();
            if (nc != null) {
                // Restore the ViewModelStore from NonConfigurationInstances
                mViewModelStore = nc.viewModelStore;
            }
            //配置中没有，则创建
            if (mViewModelStore == null) {
                mViewModelStore = new ViewModelStore();
            }
        }
        return mViewModelStore;
    }
}